/*
 * @Description:
 * @Author: Rfan
 * @Date: 2021-10-29 22:59:41
 * @LastEditTime: 2022-11-17 19:46:16
 */

import { observable, action, runInAction } from 'mobx';
import { appState } from '@/store/mobx';
import { fetchUserNavList } from '@/api/user';
import { flatRoutesToTree } from '@/utils/router';
import { IFuncNavTree } from '@/routes/interface';

// 观察者
const routerState = observable({
  navReqFlag: false,
  noLayoutList: ['/login', '/404'],
  // 原始扁平导航
  orgNavList: [],
  // 原始树结构导航
  orgNavTree: [],
  // 动态路由数据
  asyncRoutes: [],
  // 选中的子系统id
  selectSubSysId: null
});

// 方法
const routerActions = {
  /**
   * @description: 设置动态路由表
   */
  setAsyncRoutes: action((list: IFuncNavTree[]) => {
    // console.log('asyncRoutes', list);
    routerState.asyncRoutes = [...list];
  }),

  /**
   * @description: 设置动态路由导航列表
   */
  setSubSysId: action((id: number) => {
    localStorage.setItem('subSysId', id + '');
    routerState.selectSubSysId = id;
  }),

  /**
   * @description: 获取导航列表
   * @return {*}
   */
  getNavList: () => {
    if (appState.token) {
      routerState.navReqFlag = true;
      return new Promise((resolve, reject) => {
        fetchUserNavList()
          .then((res) => {
            const { data } = res;
            runInAction(() => {
              routerState.orgNavList = data;
              const treeNav = flatRoutesToTree(data);
              routerState.orgNavTree = treeNav;
              routerState.selectSubSysId =
                parseInt(localStorage.getItem('subSysId'), 10) || treeNav[0]?.id;
            });
            resolve(data || []);
          })
          .catch((err) => reject(err));
      });
    }
  }
};

export { routerState, routerActions };
